
import java.io.*;
import java.net.*;

class Client {

    public static final int NUM_RUNS = 100;

    public static void main(String args[]) throws Exception {

        while (true) {
            long pause = 0;
            Process p = Runtime.getRuntime().exec("users\n");
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = input.readLine();
            System.out.println("returned: " + line);
            line = line.replaceAll("djk1076", "");
            line = line.replaceAll(" ", "");
            if (line.length() > 0) {
                pause += 10000;//wait 10 secs if another user is on
//check cpu
                p = Runtime.getRuntime().exec("sar -u 1\n");
                input = new BufferedReader(new InputStreamReader(p.getInputStream()));
                input.readLine();
                input.readLine();
                input.readLine();
                input.readLine();
                line = input.readLine();
                String idle = line.split(" ")[line.split(" ").length - 1];
                System.out.println("idle: " + idle);
                int i = Integer.parseInt(idle);
                if (i < 50) {
                    pause += 300000;//wait an extra 5 minutes if too much cpu is used
                }
            }

            try {
                Thread.sleep(pause);
            } catch (Exception e) {
            }

            byte[] sendData = new byte[1024];
            byte[] receiveData = new byte[1024];
            DatagramSocket clientSocket = new DatagramSocket();
            InetAddress IPAddress = InetAddress.getByName("nial.cs.rit.edu");

            String sentence = Server.ASK_FOR_WORK;

            sendData = sentence.getBytes();
            System.out.println("asking for work");
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
            clientSocket.send(sendPacket);

            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            clientSocket.receive(receivePacket);
            String modifiedSentence = new String(receivePacket.getData());

            modifiedSentence = modifiedSentence.substring(1, modifiedSentence.trim().length() - 1);
            System.out.println("processing: " + modifiedSentence);
            double sum = 0;
            for (int i = 0; i < NUM_RUNS; i++) {
                Individual ind = new Individual(modifiedSentence);

                Double fitness = (Double) (ind.getFitness());
                sum += fitness;
            }
            sum = sum / NUM_RUNS;
            String response = modifiedSentence + "=" + sum;
            System.out.println("sending results");
            sendData = response.getBytes();
            sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
            clientSocket.send(sendPacket);



            clientSocket.close();
        }
    }
}
